package org.example.service.impl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.Contant.BusinessException;
import org.example.dto.UserDto;
import org.example.entity.User;
import org.example.mapper.LoginMapper;
import org.example.service.LoginService;
import org.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Resource
    private RedisTemplate<String,UserDto> redisTemplate;

    @Override
    public String login(String username, String password) {
        //根据username查询用户
        UserDto user = loginMapper.selectUserByUsername(username);
        String userPassword = user.getPassword();
        if (!userPassword.equals(password)) {
            throw new BusinessException("500","密码错误");
        }
        //将用户信息存进redis,key设置成username,过期时间10分钟
        redisTemplate.opsForValue().set(username,user,10, TimeUnit.MINUTES);
        log.info("登陆成功");
        //生成token
        return JwtUtil.createToken(user.getUsername());
    }
}
